package safeCommitter.core.diffrunbridge;

import java.lang.reflect.InvocationTargetException;
import java.util.Set;

import org.eclipse.core.runtime.CoreException;
import org.eclipse.jdt.core.IJavaProject;
import org.eclipse.ui.PartInitException;
import org.tigris.subversion.subclipse.ui.operations.CommitOperation;

import safeCommitter.core.launcher.ISCLauncher;
import safeCommitter.core.launcher.socket.SCSocketReader;
import safeCommitter.core.launcher.socket.SCVMSocketLauncher;
import safeCommitter.core.preferences.SCPreferenceConstants;
import safeCommitter.core.template.Activator;
import safeCommitter.model.adpters.ISCTest;
import safeCommitter.test.executor.launcher.internal.SCTestArgsBuilder;
import safeCommitter.test.executor.launcher.listener.SCCommitLaunchListener;
import safeCommitter.test.executor.launcher.socket.SCTestSocketReader;

public class RunTestPhaseStarter {

	// This class will be started by another JVM
	static final String MAIN_CLASS = "safeCommitter.test.executor.SCTestExecutor";

	protected SCSocketReader reader;

	/**
	 * Starts the run phase or commits the code if there's no test to be run.
	 * 
	 */
	protected void doExecute(final IJavaProject javaProject,
			final CommitOperation c, final Set<ISCTest> testUnits)
			throws PartInitException, CoreException, Exception {
		if (noTestsToBeRun(testUnits)) {
			performCommitNow(c);
		} else {
			startRunPhase(javaProject, c, testUnits);
		}
	}

	private void startRunPhase(final IJavaProject javaProject,
			final CommitOperation c, final Set<ISCTest> testUnits)
			throws PartInitException, CoreException {
		reader = new SCTestSocketReader();
		ISCLauncher launcher = new SCVMSocketLauncher(javaProject, reader);
		String filePath = SCTestArgsBuilder.getTestExecutorArgs(testUnits);
		launcher.runClazz(false, false, MAIN_CLASS, new SCCommitLaunchListener(
				reader, c), filePath);
	}

	private boolean noTestsToBeRun(final Set<ISCTest> testUnits) {
		Boolean executeNGFilesTests = Activator.getDefault()
				.getPreferenceStore().getBoolean(
						SCPreferenceConstants.P_ADD_TESTNG_XML);
		return testUnits.size() == 0 && !executeNGFilesTests;
	}

	private void performCommitNow(final CommitOperation c)
			throws InvocationTargetException, InterruptedException {
		if (c != null) {
			c.run();
		}
	}

}
